<template>
  <view class="payment-container">
    <!-- 自定义导航栏 -->
    <custom-navbar title="支付订单" backgroundColor="#42a5f5" titleColor="#ffffff"></custom-navbar>
    
    <!-- 主内容区域 -->
    <view class="main-content" style="margin-top: 64px;">
      <!-- 刷新加载框 -->
      <view class="refresh-loading" v-if="isRefreshing">
        <view class="loading-spinner"></view>
        <text class="loading-text">正在刷新...</text>
      </view>

      <!-- 订单详情 -->
      <view class="order-card">
        <view class="card-title-button">订单详情</view>

        <view class="order-info">
          <view class="info-item">
            <text class="item-label">充电站点:</text>
            <text class="item-value">{{ orderInfo.stationName }}</text>
          </view>

          <view class="info-item">
            <text class="item-label">开始时间:</text>
            <text class="item-value">{{ orderInfo.startTime || '' }}</text>
          </view>

          <view class="info-item">
            <text class="item-label">结束时间:</text>
            <text class="item-value">{{ orderInfo.endTime || '' }}</text>
          </view>

          <view class="info-item">
            <text class="item-label">充电电量:</text>
            <text class="item-value">{{ orderInfo.power }}度</text>
          </view>

          <view class="info-item amount">
            <text class="item-label">应付金额:</text>
            <text class="item-value price">¥{{ orderInfo.amount.toFixed(2) }}</text>
          </view>

        </view>
      </view>

      <!-- 支付方式 -->
      <view class="payment-method">
        <view class="method-title">支付方式</view>

        <view class="method-item" @click="selectPayment('wechat')">
          <view class="method-icon wechat">
            <text class="icon-wechat">W</text>
          </view>
          <view class="method-name">微信支付</view>
          <view class="method-select">
            <radio :checked="paymentMethod === 'wechat'" color="#3296fa" />
          </view>
        </view>

        <view class="method-item" @click="selectPayment('alipay')">
          <view class="method-icon alipay">
            <text class="icon-alipay">A</text>
          </view>
          <view class="method-name">支付宝</view>
          <view class="method-select">
            <radio :checked="paymentMethod === 'alipay'" color="#3296fa" />
          </view>
        </view>
      </view>

      <!-- 确认支付按钮 -->
      <view class="confirm-btn" @click="confirmPayment">确认支付</view>

      <!-- 底部文字 -->
      <view class="footer-text">
        点击确认支付即表示同意《充电服务协议》
      </view>
    </view>
  </view>
</template>

<script>
import { paymentOrderApi } from '@/src/api/payment0rder'
import CustomNavbar from '@/components/CustomNavbar.vue'
import { mapActions } from 'vuex'

export default {
  components: {
    CustomNavbar
  },
  data() {
    return {
      orderInfo: {
        stationName: '科技园充电站',
        startTime: '',
        endTime: '',
        power: 50,
        amount: 0.01,
        orderId: ''
      },
      paymentMethod: 'wechat',
      isLoading: false,
      loadError: false,
      isRefreshing: false
    }
  },
  onLoad(options) {
    // 页面加载时获取订单状态信息
    this.fetchOrderState()
  },
  // 启用下拉刷新
  onPullDownRefresh() {
    // 下拉刷新时重新获取数据
    this.fetchOrderState(true)
  },
  methods: {
    ...mapActions('charger', ['clearPileId', 'clearSocketSn']),

    goBack() {
      const pages = getCurrentPages();
      if (pages.length > 1) {
        uni.navigateBack();
      } else {
        // 若路由栈只有一个页面，可跳转到首页
        uni.switchTab({
          url: '/pages/index/index', // 替换为你的首页路径
          success: () => {
            // 成功跳转到首页
          },
          fail: (err) => {
            // 跳转到首页失败
          }
        });
      }
    },

    // 获取订单状态信息
    fetchOrderState(isPullDown = false) {
      this.isLoading = true;
      this.loadError = false;

      if (isPullDown) {
        this.isRefreshing = true;
      } else {
        uni.showLoading({
          title: '加载订单信息...'
        });
      }

      paymentOrderApi.getOrderDetail()
        .then(res => {
          console.log('订单状态信息:', res);
          if (res.code === 200 && res.data) {
            console.log('订单状态信息:', res.data);
            // 更新订单信息
            this.orderInfo = {
              startTime: res.data.startTime,
              endTime: res.data.endTime,
              amount: res.data.paymentAmount,
              orderId: res.data.id,
              orderSn: res.data.orderSn
            };
          }
        })
        .catch(err => {
          this.loadError = true;

          uni.showToast({
            title: '获取订单信息失败，下拉可刷新重试',
            icon: 'none',
            duration: 2500
          });
        })
        .finally(() => {
          this.isLoading = false;
          this.isRefreshing = false;
          uni.hideLoading();

          // 如果是下拉刷新，停止下拉刷新动画
          if (isPullDown) {
            uni.stopPullDownRefresh();
          }
        });
    },

    selectPayment(method) {
      this.paymentMethod = method;
    },
    confirmPayment() {
      // cursor: Step 1 - 参数校验
      // 检查支付金额是否为0
      if (this.orderInfo.amount <= 0) {
        uni.showToast({
          title: '支付金额不能为0',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 检查支付方式是否为微信支付
      if (this.paymentMethod !== 'wechat') {
        uni.showToast({
          title: '目前仅支持微信支付',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // cursor: Step 2 - 开始支付流程，显示加载中状态
      uni.showLoading({
        title: '正在发起支付...'
      });

      // cursor: Step 3 - 调用后端支付接口获取支付参数
      console.log('发起支付请求，订单ID:', this.orderInfo.orderId);
      paymentOrderApi.pay(this.orderInfo.orderId)
        .then(res => {
          uni.hideLoading();

          // cursor: Step 4 - 检查响应状态
          if (res.code !== 200 || !res.data) {
            if (res.code === 201) {
              // cursor: 支付单已创建但未完成，直接进入轮询状态
              uni.showToast({
                title: '订单已提交，等待支付结果',
                icon: 'none',
                duration: 2000
              });
              return this.pollPaymentStatus(5);
            }
            throw new Error(res.msg || '获取支付参数失败');
          }

          // cursor: Step 5 - 获取支付参数
          const payParams = res.data;
          console.log('获取到支付参数:', payParams);

          // cursor: Step 6 - 调用微信支付API
          // 提示: 确保payParams包含appId, timeStamp, nonceStr, package, signType, paySign
          return new Promise((resolve, reject) => {
            // cursor: 微信小程序支付API调用
            uni.requestPayment({
              provider: 'wxpay',
              timeStamp: payParams.timeStamp,
              nonceStr: payParams.nonceStr,
              package: payParams.packageVal,
              signType: payParams.signType,
              paySign: payParams.paySign,
              success: (res) => {
                console.log('支付成功返回:', res);
                resolve(res);
              },
              fail: (err) => {
                console.error('支付失败:', err);
                if (err.errMsg.indexOf('cancel') > -1) {
                  reject(new Error('用户取消支付'));
                } else {
                  reject(new Error('支付失败: ' + err.errMsg));
                }
              }
            });
          });
        })
        .then(() => {
          // cursor: Step 7 - 支付成功，开始轮询订单状态
          uni.showLoading({
            title: '正在确认支付状态...'
          });

          // cursor: Step 8 - 轮询支付状态 (最多尝试5次)
          return this.pollPaymentStatus(5);
        })
        .then(() => {
          // cursor: Step 9 - 支付确认成功
          uni.hideLoading();
          // 清除充电桩ID和插枪ID
          this.clearPileId();
          this.clearSocketSn();
          console.log('支付完成，已清除充电桩ID和插枪ID');
          
          uni.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 2000
          });

          // cursor: Step 10 - 跳转到我的页面
          setTimeout(() => {
            const targetPath = '/pages/mine/mine';
            uni.switchTab({
              url: targetPath,
              success: () => {
                setTimeout(() => {
                  uni.$emit('updateTabBar');
                  if (typeof uni.setStorageSync === 'function') {
                    uni.setStorageSync('currentTabPath', targetPath);
                  }
                }, 100);
              }
            });
          }, 2000);
        })
        .catch(err => {
          // cursor: Step 11 - 错误处理
          uni.hideLoading();
          console.error('支付流程异常:', err);

          let errorMsg = '支付失败';
          if (err && err.message) {
            if (err.message === '用户取消支付') {
              errorMsg = '支付已取消';
            } else {
              errorMsg = '支付失败';
            }
          }

          uni.showToast({
            title: errorMsg,
            icon: 'none',
            duration: 3000
          });
        });
    },

    // cursor: 轮询支付状态的方法
    pollPaymentStatus(maxAttempts = 5, interval = 1000) {
      return new Promise((resolve, reject) => {
        let attempts = 0;
        
        const checkStatus = () => {
          attempts++;
          console.log(`第${attempts}次查询支付状态`);
          
          paymentOrderApi.getPayState(this.orderInfo.orderSn)
            .then(res => {
              if (!res || res.code !== 200) {
                // cursor: 特殊处理支付状态响应码
                if (res && res.code === 201) {
                  // cursor: 201 表示支付进行中，继续轮询
                  if (attempts >= maxAttempts) {
                    uni.showToast({
                      title: '支付处理中，请稍后查看订单状态',
                      icon: 'none',
                      duration: 3000
                    });
                    resolve(); // 结束轮询但不视为错误
                    return;
                  }
                  // 继续轮询
                  setTimeout(checkStatus, interval);
                  return;
                }
                
                throw new Error(res?.msg || '查询支付状态失败');
              }
              
              // cursor: 假设后端返回的支付状态码： 1=支付中，2=支付成功，3=支付失败，4=已关闭
              const payStatus = res.data?.payStatus;
              const statusMessage = res.data?.statusMessage || '';
              
              console.log(`支付状态: ${payStatus}, 消息: ${statusMessage}`);
              
              switch (payStatus) {
                case 2: // 支付成功
                  // 清除充电桩ID和插枪ID
                  this.clearPileId(); // 清除充电桩ID
                  this.clearSocketSn(); // 清除插枪ID
                  console.log('支付成功，已清除充电桩ID和插枪ID');
                  
                  uni.showToast({
                    title: statusMessage || '支付成功',
                    icon: 'success',
                    duration: 2000
                  });
                  resolve();
                  break;
                
                case 3: // 支付失败
                  uni.showToast({
                    title: statusMessage || '支付失败，请重试',
                    icon: 'none',
                    duration: 3000
                  });
                  reject(new Error(statusMessage || '支付失败'));
                  break;
                
                case 4: // 已关闭
                  uni.showToast({
                    title: statusMessage || '订单已关闭',
                    icon: 'none',
                    duration: 3000
                  });
                  reject(new Error(statusMessage || '订单已关闭'));
                  break;
                
                case 1: // 支付中
                default:
                  if (attempts >= maxAttempts) {
                    uni.showToast({
                      title: '支付状态确认超时，请稍后查看订单',
                      icon: 'none',
                      duration: 3000
                    });
                    resolve(); // 超时但不视为错误，让用户可以继续操作
                  } else {
                    // 继续轮询
                    setTimeout(checkStatus, interval);
                  }
              }
            })
            .catch(err => {
              console.error('查询支付状态出错:', err);
              if (attempts >= maxAttempts) {
                uni.showToast({
                  title: '无法确认支付状态，请稍后检查订单',
                  icon: 'none',
                  duration: 3000
                });
                reject(err);
              } else {
                // 请求失败但仍继续尝试
                setTimeout(checkStatus, interval);
              }
            });
        };
        
        // 开始查询前显示加载中
        uni.showLoading({
          title: '正在查询支付状态...'
        });
        
        checkStatus();
      }).finally(() => {
        // 无论结果如何，确保加载提示被关闭
        uni.hideLoading();
      });
    }
  }
}
</script>

<style lang="scss">
.payment-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  overflow: hidden;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #42a5f5;
  display: flex;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;

  .nav-content {
    width: 100%;
    height: 88rpx;
    position: relative;
    margin-top: calc(var(--status-bar-height) + 30rpx);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 24rpx;
    box-sizing: border-box;
  }

  .back-icon {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;

    image {
      width: 24px;
      height: 24px;
      opacity: 0.9;
    }
  }

  .header-title {
    font-size: 18px;
    font-weight: 500;
    text-align: center;
    flex: 1;
    margin: 0 32px;
    color: #fff;
  }
}

.main-content {
  position: absolute;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  padding: 12px 16px;
  overflow-y: auto;
}

.refresh-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px;
  margin-bottom: 12px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;

  .loading-spinner {
    width: 30px;
    height: 30px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #42a5f5;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 8px;
  }

  .loading-text {
    font-size: 14px;
    color: #666;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }
}

.error-notice {
  background-color: #fef0f0;
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;

  .error-icon {
    width: 24px;
    height: 24px;
    background-color: #f56c6c;
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    margin-right: 10px;
  }

  .error-text {
    font-size: 14px;
    color: #f56c6c;
  }
}

.order-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 16px;
  margin-bottom: 16px;

  .card-title-button {
    font-size: 16px;
    font-weight: 500;
    text-align: center;
    padding: 12px 0;
    background-color: #42a5f5;
    color: #fff;
    margin-bottom: 15px;
    border-radius: 12px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    &:active {
      opacity: 0.9;
      transform: scale(0.98);
    }
  }

  .order-info {
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    padding: 16px;
    margin-bottom: 16px;

    .info-item {
      display: flex;
      margin-bottom: 15px;

      &:last-child {
        margin-bottom: 0;
      }

      &.amount {
        border-top: 1px solid #f5f5f5;
        padding-top: 10px;
        margin-top: 5px;
      }

      .item-label {
        color: #333;
        min-width: 80px;
      }

      .item-value {
        flex: 1;
        color: #666;

        &.price {
          color: #ff6b00;
          font-weight: bold;
          font-size: 18px;
        }
      }
    }
  }
}

.payment-method {
  margin-bottom: 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

  .method-title {
    font-size: 16px;
    padding: 15px;
    color: #333;
  }

  .method-item {
    display: flex;
    align-items: center;
    padding: 15px;
    border-top: 1px solid #f5f5f5;

    .method-icon {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-weight: bold;
      margin-right: 10px;

      &.wechat {
        background-color: #09bb07;
      }

      &.alipay {
        background-color: #1677ff;
      }
    }

    .method-name {
      flex: 1;
      font-size: 16px;
      color: #333;
    }
  }
}

.confirm-btn {
  margin-top: auto;
  margin-bottom: 20px;
  height: 45px;
  line-height: 45px;
  text-align: center;
  background-color: #ff6b00;
  color: #fff;
  font-size: 16px;
  border-radius: 45px;
  box-shadow: 0 4rpx 10rpx rgba(255, 106, 60, 0.3);
}

.footer-text {
  text-align: center;
  font-size: 12px;
  color: #999;
  margin-bottom: 20px;
}
</style>